<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>角色信息管理</title>
    <link rel="stylesheet" th:href="@{/js/layui/css/layui.css}">
    <link href="../img/manage.ico" rel="icon" type="image/x-ico">
</head>
<body class="layui-layout-body">
<div  class="layui-layout layui-layout-admin">
    <div>
        <!--数据总条数-->
        <input type="hidden" id="number" th:value="${number}">
        <!--搜索框-->
        <form class="layui-form" id="searchform">
            <div class="layui-form-item" style="display: inline;">
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" name="s_rolename" id="s_rolename" placeholder="请输入角色名" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <div class="layui-btn" data-type="reload" lay-filter="rechar_btn" id="search_btn">搜索</div>
                    </div>
                </div>
            </div>
        </form>
        <!--内容主体区域-->
        <table id="tb-user" lay-filter="tb-user"></table>
    </div>
    <!--    编辑表单-->
    <div class="layui-row" id="editform" style="display: none;padding-left: 20px;padding-right: 20px;">
            <form class="layui-form layui-form-pane" id="saveUser" style="margin-top: 20px;" enctype="multipart/form-data">
                <div class="layui-form-item" style="display: none">
                    <label class="layui-form-label">id</label>
                    <div class="layui-input-block">
                        <input type="text" name="id" id="id" required lay-verify="required" autocomplete="off"
                               class="layui-input" readonly>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色名</label>
                    <div class="layui-input-block">
                        <input type="text" name="role_name" id="role_name" required lay-verify="required" autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <input type="text" name="remark" id="remark" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item" id="check">
                    <div class="layui-input-block">
                        <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="saveUser" style="margin-left: 285px;">保存
                        </button>
                    </div>
                </div>
            </form>
    </div>
    <!--    添加信息-->
    <div class="layui-row" id="addform" style="display:none;padding-left: 50px;">
        <div class="layui-col-md10">
            <form class="layui-form layui-form-pane" id="addUser" style="margin-top: 20px;"
                  enctype="multipart/form-data">
                <div class="layui-form-item">
                    <label class="layui-form-label">角色名&nbsp;<b style="color: red">*</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="a_role_name" id="a_role_name" placeholder="请输入角色名" required lay-verify="required" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">选择权限&nbsp;<b style="color: red">*</b></label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="a_permission" th:each="permission:${permissions}" th:value="${permission.id}" th:title="${permission.permission_name}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <input type="text" name="a_remark" id="a_remark" placeholder="请输入备注" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block" style="margin-left: 210px;">
                        <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="addUser">保存</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <!--   重置权限 -->
    <div class="layui-row" id="resetform" style="display: none;padding-left: 20px;padding-right: 20px;">
        <form class="layui-form layui-form-pane" id="resetUser" style="margin-top: 20px;" enctype="multipart/form-data" lay-filter="example">
            <div class="layui-form-item" style="display: none">
                <label class="layui-form-label">id</label>
                <div class="layui-input-block">
                    <input type="text" name="r_id" id="r_id" autocomplete="off" class="layui-input" readonly>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择权限</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="permission" th:each="permission:${permissions}" th:value="${permission.id}" th:title="${permission.permission_name}">
                </div>
            </div>
            <input type="hidden" id="arr" name="arr">
            <div class="layui-form-item">
                <div class="layui-input-block"   style="margin-left: 295px;">
                    <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="resetUser">保存</button>
                </div>
            </div>
        </form>
    </div>
    <!--    新增/删除按钮-->
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon">&#xe608;</i>新增</button>
            <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="remove"><i class="layui-icon">&#xe640;</i>删除</button>
        </div>
    </script>
    <!--    编辑按钮-->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon">&#xe642;</i>编辑</a>
    </script>
    <!--    重置权限-->
    <script type="text/html" id="barDemos">
        <a class="layui-btn layui-btn-sm layui-btn-danger" lay-event="reset"><i class="layui-icon">&#xe673;</i>重置权限</a>
    </script>
</div>
<script src="../js/jquery-2.1.0.min.js"></script>
<script src="../js/layui/layui.all.js"></script>
<script>
    var element, layer, laydate, table, form;

    $(function () {
        // 使用模块
        layui.use(['element', 'layer', 'laydate', 'table', 'form'], function () {
            element = layui.element;
            layer = layui.layer;
            table = layui.table;
            form = layui.form;
        });
        var number=document.getElementById("number").value;
        // 初始化表格
        var userTable = table.render({
            elem: '#tb-user'
            , height: 535
            , even: true
            , toolbar: '#toolbarDemo'
            , url: '/role/lists' //请求数据接口
            , limit: 10//要传向后台的每页显示条数
            //,page:true(自带的这个要注掉)
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']//自定义分页布局
                , limits: [10, 20, 30, 40, 50, number]
                , first: false //不显示首页
                , last: false //不显示尾页
            }
            , id: 'testReload'
            , cols: [[ //表头
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'id', sort: true ,hide: true}
                , {field: 'role_name', title: '角色名', sort: true , width:150}
                , {field: 'permission', title: '权限'}
                , {field: 'remark', title: '备注' , width:150}
                , {fixed: 'right', title: '编辑', toolbar: '#barDemo' , width:100},
                , {fixed: 'right', title: '重置权限', toolbar: '#barDemos' , width:120}
            ]]
        });

        //表格重载
        var $ = layui.$, active = {
            reload: function () {
                var s_rolename = $('#s_rolename');

                //执行重载
                table.reload('testReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , url: "/role/search"
                    , method: "POST"
                    , where: {
                        role_name: s_rolename.val()
                    }
                });
            }
        };

        $('#search_btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        // 监听编辑按钮事件
        table.on('tool(tb-user)', function (obj) {
            var data = obj.data;
            // 修改
            if (obj.event === 'edit') {
                $("#id").val(data.id);
                $("#role_name").val(data.role_name);
                $("#remark").val(data.remark);

                layer.open({
                    type: 1,
                    maxmin: true,
                    offset: '10px',
                    title: "修改信息",
                    area: ['500px', '400px'],
                    content: $("#editform")
                });
            }else if(obj.event === 'reset'){
                $("#r_id").val(data.id);

                layer.open({
                    type: 1,
                    maxmin: true,
                    offset: '10px',
                    title: "重置权限",
                    area: ['500px', '300px'],
                    content: $("#resetform")
                });
            }
        });

        //监听表单重置提交
        form.on('submit(resetUser)', function (data) {
            var arrs = new Array();
            var id=document.getElementById("r_id");
            //将角色id传给arrs[0]
            arrs[0]=id.value;
            //获取checkbox[name='permission']的值，获取所有选中的复选框，并将其值放入数组中
            $("input:checkbox[name='permission']:checked").each(function(i){
                arrs[i+1] = $(this).val();
            });
            $.ajax({
                url: "/role/reset?arr="+arrs,
                type: "POST",
                async: false,
                dataType: "json",
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                success: function (result) {
                    if (result.code == 100) {
                        layer.msg("修改成功！", {icon: 6, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    }else if (result.code == 200){
                        layer.msg("超级管理员无法修改！", {icon: 5, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    } else {
                        layer.msg("操作失败！", {icon: 5, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    }
                }
            })
            return false;
        });


        //监听表单修改提交
        form.on('submit(saveUser)', function (data) {
            var forms = document.getElementById("saveUser");
            var formdata = new FormData(forms);
            $.ajax({
                url: "/role/edit",
                type: "POST",
                data: formdata,
                async: false,
                dataType: "json",
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                success: function (result) {
                    if (result.code == 100) {
                        layer.msg("修改成功！", {icon: 6, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    } else if (result.code == 200){
                        layer.msg("超级管理员无法修改！", {icon: 5, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    }else {
                        layer.msg("操作失败！", {icon: 5, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    }
                }
            })
            return false;
        });

        // 监听添加按钮事件
        table.on('toolbar(tb-user)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                var checkData = checkStatus.data;
                var ids = [];
                switch (obj.event) {
                    // 新增
                    case 'add':
                        $("#a_role_name").val('');
                        $("#a_remark").val('');

                        layer.open({
                            type: 1,
                            maxmin: true,
                            offset: '10px',
                            title: "添加信息",
                            area: ['500px', '470px'],
                            content: $("#addform")
                        });
                        break;
                    case 'remove':
                        // 删除
                        if (checkData.length == 0) {
                            layer.alert('请选择要操作的行');
                        } else {
                            layer.confirm('确定要删除吗？', function (index) {
                                for (var i = 0; i < checkData.length; i++) {
                                    ids.push(checkData[i].id);
                                }
                                //layer.alert(JSON.stringify(ids));
                                $.ajax({
                                    url: '/role/remove',
                                    type: 'POST',
                                    contentType: "application/json",
                                    dataType: "json",
                                    data: JSON.stringify(ids),
                                    success: function (result) {
                                        if (result.code == 100) {
                                            layer.msg("删除成功！", {icon: 6, time: 1000});
                                            setTimeout(function () {
                                                layer.closeAll();//关闭所有的弹出层
                                                userTable.reload();
                                            }, 1000);
                                        } else {
                                            layer.msg("删除失败！", {icon: 5, time: 1000});
                                            setTimeout(function () {
                                                layer.closeAll();//关闭所有的弹出层
                                                userTable.reload();
                                            }, 1000);
                                        }
                                    }
                                });
                            });
                        }
                        break;
                        case 'download':
                            alert("test");
                }
            }
        );

        //监听表单添加提交
        form.on('submit(addUser)', function (data) {
            var forms = document.getElementById("addUser");
            var formdata = new FormData(forms);
            var arrs = new Array();
            //获取checkbox[name='permission']的值，获取所有选中的复选框，并将其值放入数组中
            $("input:checkbox[name='a_permission']:checked").each(function(i){
                arrs[i] = $(this).val();
            });
            $.ajax({
                url: "/role/add?arr="+arrs,
                type: "POST",
                data: formdata,
                async: false,
                dataType: "json",
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                success: function (result) {
                    if (result.code === 100) {
                        layer.msg("添加成功！", {icon: 6, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    } else if(result.code === 200){
                        layer.msg("角色已存在，添加失败！", {icon: 5, time: 1000});
                        setTimeout(function () {
                            // layer.closeAll();//关闭所有的弹出层
                            // userTable.reload();
                        }, 1000);
                    }else{
                        layer.msg("添加失败！", {icon: 5, time: 1000});
                        setTimeout(function () {
                            layer.closeAll();//关闭所有的弹出层
                            userTable.reload();
                        }, 1000);
                    }
                }
            })
            return false;
        })
    })
</script>
</body>
</html>